import stat

import paramiko
import os
from configs import logger


# ftp_config = {
#     'hostname': '192.168.11.180',
#     'username': 'jiayen',
#     'password': '5768178',
#     'port': 22,
# }


# 上传文件进度反馈
def put_call_back(start, end):
    process = (float(start) / end) * 100
    print("当前进度为: %.2f %%" % process)


def upload_file(local_file_path, remote_file_path, ftp_config=None):
    '''
    ftp上传文件
    :param local_file_path:
    :param remote_file_path:
    :return:
    '''
    hostname = ftp_config['hostname']
    username = ftp_config['username']
    password = ftp_config['password']
    port = ftp_config['port']
    logger.debug("当前服务器ip为:{}", hostname)
    # 登录ftp
    transport = paramiko.Transport((hostname, port))
    transport.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(transport)
    # 开始上传文件
    base_path = os.path.dirname(remote_file_path)
    try:
        sftp.stat(base_path)
        print("exist")
    except IOError:
        print("not exist")
        print('base_path', base_path)
        sftp.mkdir(base_path)
    sftp.put(local_file_path, remote_file_path, put_call_back)
    print(sftp.listdir(base_path))
    sftp.close()
    transport.close()
    logger.debug("上传成功，上传路径为:{}", remote_file_path)


def download_file(local_file_path, remote_file_path, ftp_config=None):
    '''
    ftp下载文件
    :param local_file_path:
    :param remote_file_path:
    :return:
    '''
    hostname = ftp_config['hostname']
    username = ftp_config['username']
    password = ftp_config['password']
    port = ftp_config['port']
    # 登录ftp
    transport = paramiko.Transport((hostname, port))
    transport.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(transport)
    # 开始下载文件
    try:
        sftp.get(remote_file_path, local_file_path, put_call_back)
        logger.debug('sftp服务器文件 {} 下载成功!\n该文件保存本地位置是 {} !\n'.format(remote_file_path, local_file_path))
        return True
    except Exception as e:
        logger.error('%s下载出错!:\n' % (remote_file_path), e)
        # 删除文件
        os.remove(local_file_path)
        logger.exception(e)
        sftp.close()
        transport.close()
    sftp.close()
    transport.close()
    return False

def sftp_download_folder(local_file_path, remote_file_path, ftp_config=None):
    '''
    下载文件夹下所有的数据
    :param hostname:
    :param port:
    :param username:
    :param password:
    :param remote_dir:
    :param local_dir:
    :return:
    '''
    hostname = ftp_config['hostname']
    username = ftp_config['username']
    password = ftp_config['password']
    port = ftp_config['port']
    if port is None:
        port=22
    try:
        # 创建一个 SSH 客户端对象
        ssh = paramiko.SSHClient()
        # 自动添加主机到known_hosts文件中
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接到远程服务器
        ssh.connect(hostname, port, username, password)

        # 创建一个 SFTP 客户端对象
        sftp = ssh.open_sftp()
        # 确保本地目录存在
        if not os.path.exists(local_file_path):
            os.makedirs(local_file_path)
        # 遍历远程目录中的文件
        def get_list_files(file_path):
            '''
            递归遍历
            :param file_path:  文件位置
            :return:
            '''
            for item in sftp.listdir_attr(file_path):
                try:
                    remote_path = '%s/%s'%(file_path,item.filename)
                    local_path = remote_path.replace(remote_file_path,local_file_path).encode('utf-8')
                    if s_isdir(item):
                        # 如果是目录，则递归调用
                        get_list_files(remote_path)
                    else:
                        # 如果是文件，则下载文件
                        logger.debug(f"Downloading {remote_path} to {local_path}")
                        local_dir = os.path.dirname(local_path)
                        if not os.path.exists(local_dir):
                            os.makedirs(local_dir)
                        if not os.path.exists(local_path):
                            sftp.get(remote_path, local_path,put_call_back)
                        else:
                            logger.debug('{}已经存在，将不再重复下载',local_path)
                except Exception as e:
                    logger.exception(e)
        get_list_files(remote_file_path)
        # 关闭 SFTP 和 SSH 客户端
        sftp.close()
        ssh.close()
        logger.debug("文件下载完成")
    except Exception as e:
       logger.exception(e)
def s_isdir(item):
    return  stat.S_ISDIR(item.st_mode)


from hetong.config import ftp_config

if __name__ == '__main__':
    local_file_path = r"D:\gitwork\hr\tool\audit-tools-platform\web\admin\target\atp-admin.jar"  # 替换为本地文件的路径
    remote_file_path = '/data/docker/aip-server/atp-admin_new.jar'  # 替换为远程文件在SFTP服务器上的路径
    # sftp_download_folder(local_file_path, remote_file_path, ftp_config_ditui_result)
    upload_file(local_file_path,remote_file_path,ftp_config=ftp_config_ditui_result)
    # # download_file("remote_file.zip", remote_file_path)
    # print(os.path.dirname(local_file_path))
    # print(os.path.dirname(local_file_path))
